from pymongo import MongoClient
from pymongo.errors import ConnectionFailure
from pprint import pprint
# MongoDB连接配置
MONGO_HOST = "101.227.69.34"
MONGO_PORT = 2929
MONGO_USER = "admin"
MONGO_PASS = "admin"
DB_NAME = "hr"  # 指定数据库名
COLLECTION_NAME = "employees"  # 指定集合名
try:
    # 创建MongoDB客户端连接
    client = MongoClient(
        host=MONGO_HOST,
        port=MONGO_PORT,
        username=MONGO_USER,
        password=MONGO_PASS,
        authSource="admin"
    )
    # 测试连接
    client.admin.command("ping")
    print("MongoDB连接成功！")
    # 获取数据库和集合
    db = client[DB_NAME]
    collection = db[COLLECTION_NAME]
    # 查询所有数据
    print(f"{DB_NAME}.{COLLECTION_NAME} 中的所有员工数据:")
    all_employees = collection.find()
    # 打印查询结果
    for idx, employee in enumerate(all_employees, 1):
        print(f"\n员工 #{idx}:")
        pprint(employee)
    # 打印总记录数
    print(f"\n总记录数: {collection.count_documents({})}")
except ConnectionFailure as e:
    print(f"MongoDB连接失败: {e}")
except Exception as e:
    print(f"发生错误: {e}")
finally:
    # 关闭连接
    if "client" in locals():
        client.close()